import Vue from 'vue';

// 第01步：导入第三方路由模块（依赖包）
import VueRouter from 'vue-router';

import store from "@/store/index.js";

import HomeView from '@/views/home/HomeView.vue';
import SearchView from "@/views/search/SearchView.vue";
import DetailView from "@/views/detail/DetailView.vue";
import ShoppingView from "@/views/detail/shopping/ShoppingView.vue";
import CartView from "@/views/cart/CartView.vue";
import TradeView from "@/views/trade/TradeView.vue";
import PayView from "@/views/pay/PayView.vue";
import WechatView from "@/views/pay/wechat/WechatView.vue";
import CenterView from "@/views/center/CenterView.vue";
import LoginView from "@/views/login/LoginView.vue";
import RegisterView from "@/views/register/RegisterView.vue";
import MyOrderView from "@/views/center/my/MyOrderView.vue";
import TeamOrderView from "@/views/center/team/TeamOrderView.vue";

// 第02步：调用Vue.use()函数，把VueRouter安装为Vue插件
Vue.use(VueRouter);

// 第08步：配置路由规则（前面需要加斜杠（/））
const routes = [
    {
        path: '/',
        redirect: '/home'
    },
    {
        path: '/home',
        name: 'home',
        component: HomeView,
        meta: {
            title: '商城首页'
        }
    },
    {
        path: '/search',
        name: 'search',
        component: SearchView,
        meta: {
            title: '搜索页面'
        }
    },
    {
        path: '/detail/:skuId?',
        name: 'detail',
        component: DetailView,
        meta: {
            title: '详情页面'
        }
    },
    {
        path: '/cartsuccess',
        name: 'cartsuccess',
        component: ShoppingView,
        meta: {
            title: '购物成功'
        }
    },
    {
        path: '/cart',
        name: 'cart',
        component: CartView,
        meta: {
            title: '订单页面'
        }
    },
    {
        path: '/login',
        name: 'login',
        component: LoginView,
        meta: {
            title: '登录页面'
        }
    },
    {
        path: '/register',
        name: 'register',
        component: RegisterView,
        meta: {
            title: '注册页面'
        }
    },
    {
        path: '/trade',
        name: 'trade',
        component: TradeView,
        meta: {
            title: '交易页面'
        }
    },
    {
        path: '/pay',
        name: 'pay',
        component: PayView,
        meta: {
            title: '支付页面'
        }
    },
    {
        path: '/paysuccess',
        name: 'paysuccess',
        component: WechatView,
        meta: {
            title: '支付成功'
        }
    },
    {
        path: '/center',
        name: 'center',
        component: CenterView,
        children: [
            {
                path: '/center',
                redirect: '/center/myorder'
            },
            // 子级路由前面不需要加斜杠（/）哈！底层遍历的时候会自动加上哈！！！
            {
                path: 'myorder',
                name: 'myorder',
                component: MyOrderView,
                meta: {
                    title: '我的订单'
                }
            },
            // 子级路由前面不需要加斜杠（/）哈！底层遍历的时候会自动加上哈！！！
            {
                path: 'teamorder',
                name: 'teamorder',
                component: TeamOrderView,
                meta: {
                    title: '团购订单'
                }
            }
        ],
        meta: {
            title: '订单中心'
        }
    },
    {
        path: '/about',
        name: 'about',
        component: () => import('@/views/AboutView.vue')
    }
];

// 重写原型对象push()方法，replace()方法
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

VueRouter.prototype.push = function (to, onComplete, onAbort) {
    if (onComplete && onAbort) {
        originPush.call(this, to, onComplete, onAbort);
    } else {
        originPush.call(this, to, () => {
        }, () => {
        });
    }
}

VueRouter.prototype.replace = function (to, onComplete, onAbort) {
    if (onComplete && onAbort) {
        originReplace.call(this, to, onComplete, onAbort);
    } else {
        originReplace.call(this, to, () => {
        }, () => {
        });
    }
}

// 第03步：创建路由模块实例对象
const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: routes,
    scrollBehavior() {
        return {x: 0, y: 0};
    }
});

// 第03步：全局前置守卫（全局前置监听器）
// 第03步：全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach(async function (to, from, next) {
    let hasToken = store.state.user.token;
    console.log('登录密钥：', hasToken);
    let hasNickName = store.state.user.nickName;
    console.log('登录昵称：', hasNickName);
    if (hasToken) {
        if (to.path === '/login') {
            next('/home');
        } else {
            if (hasNickName) {
                next();
            } else {
                try {
                    await store.dispatch('getUserInfo');
                    next();
                } catch (error) {
                    await store.dispatch('logout');
                    next('/login');
                }
            }
        }
    } else {
        let toPath = to.path;
        if (toPath.indexOf('trade') !== -1 || toPath.indexOf('pay') !== -1 || toPath.indexOf('center') !== -1) {
            next(`/login?redirect=${toPath}`);
        } else {
            next();
        }
    }
});

// 第03步：全局后置守卫（全局后置监听器）
// 第03步：全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
router.afterEach(function (to, from) {
    console.log('After Each: ', to.name, from.name);
    console.log('After Each: ', to.path, from.path);
    console.log('After Each: ', to.fullPath, from.fullPath);
    document.title = to.meta.title || '如果Meta没有标题就用我吧';
});

// 第04步：向外共享路由的实例对象
export default router;



